package com.tukez.tmdb.util
import net.liftweb.json.CustomSerializer
import net.liftweb.json.JsonAST.JString
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import org.joda.time.LocalDate
import net.liftweb.json.JsonAST.JInt
import net.liftweb.json.JsonAST.JNull
import org.joda.time.Duration
import net.liftweb.json.MappingException

object DateTimeSerializer extends CustomSerializer[DateTime](format => (
  {
    case JString(s) => {
      val millis = format.dateFormat.parse(s).map(_.getTime).getOrElse(throw new MappingException("Invalid date format " + s))
      new DateTime(millis)
    }
    case JNull => null
  },
  {
    case d: DateTime => JString(format.dateFormat.format(d.toDate))
  }
))

object LocalDateSerializer extends CustomSerializer[LocalDate](format => (
  {
    case JString(s) => DateTimeFormat.forPattern("yyyy-MM-dd").parseLocalDate(s)
    case JNull => null
  },
  {
    case d: LocalDate => JString(format.dateFormat.format(d.toDate))
  }
))

object DurationSerializer extends CustomSerializer[Duration](format => (
  {
    case JInt(m) => Duration.standardMinutes(m.longValue)
    case JNull => null
  },
  {
    case d: Duration => JInt(d.toStandardMinutes.getMinutes)
  }
))